package com.sunshine.lnuplus.view.AppSetting;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar;
import com.sunshine.lnuplus.R;
import com.sunshine.lnuplus.databinding.ActivityAppSettingBinding;
import com.sunshine.lnuplus.utils.FileHelper;
import com.sunshine.lnuplus.utils.PermissionHelper;
import com.sunshine.lnuplus.utils.StatusBarUtils;
import com.sunshine.lnuplus.utils.TagHelper;
import com.sunshine.lnuplus.view.BaseActivity;
import com.sunshine.lnuplus.view.Main.MainActivity;

import java.io.File;

public class AppSettingActivity extends BaseActivity implements View.OnClickListener {

    private AppSettingViewModel viewModel;
    private ActivityAppSettingBinding binding;
    private AlertDialog.Builder builder;
    private AlertDialog dialog;
    private int themeNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_app_setting);
        viewModel = ViewModelProviders.of(this).get(AppSettingViewModel.class);
        StatusBarUtils.with(this).setColor(-2).init();

        themeNum = viewModel.getTheme();

        viewModel.getEverydayBackground().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                binding.checkBoxEverydayBackground.setChecked(aBoolean);
            }
        });

        viewModel.getCheckUpdate().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                binding.checkBoxCheckUpdate.setChecked(aBoolean);
            }
        });

        binding.buttonAppTheme.setOnClickListener(this);
        binding.buttonEverydayBackground.setOnClickListener(this);
        binding.buttonUserBackground.setOnClickListener(this);
        binding.buttonClearUserBackground.setOnClickListener(this);
        binding.buttonCheckUpdate.setOnClickListener(this);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_appTheme:
                initThemeDialog();
                break;
            case R.id.button_everydayBackground:
                binding.checkBoxEverydayBackground.setChecked(!viewModel.getEverydayBackground().getValue());
                viewModel.getEverydayBackground().setValue(!viewModel.getEverydayBackground().getValue());
                viewModel.saveEverydayBackground();
                setResult(TagHelper.APPSETTING);
                break;
            case R.id.button_userBackground:
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},TagHelper.APPSETTING);
                break;
            case R.id.button_clearUserBackground:
                FileHelper.userBackgroundClear(getApplicationContext());
                Snackbar.make(binding.appSettingLayout,"清除成功~",Snackbar.LENGTH_SHORT).show();
                setResult(TagHelper.APPSETTING);
                break;
            case R.id.button_checkUpdate:
                binding.checkBoxCheckUpdate.setChecked(!viewModel.getCheckUpdate().getValue());
                viewModel.getCheckUpdate().setValue(!viewModel.getCheckUpdate().getValue());
                viewModel.saveCheckUpdate();
                break;
            case R.id.button_lesson_1:
                themeNum = 1;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
            case R.id.button_lesson_2:
                themeNum = 2;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
            case R.id.button_lesson_3:
                themeNum = 3;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
            case R.id.button_lesson_4:
                themeNum = 4;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
            case R.id.button_lesson_6:
                themeNum = 5;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
            case R.id.button_lesson_7:
                themeNum = 6;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
            case R.id.button_lesson_8:
                themeNum = 7;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
            case R.id.button_lesson_9:
                themeNum = 8;
                dialog.setTitle("已选择主题："+getThemeName(themeNum));
                break;
        }
    }

    private void initThemeDialog() {
        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        View dialogView = inflater.inflate(R.layout.dialog_choose_theme,null);
        //theme dialog中监听
        Button black = dialogView.findViewById(R.id.button_lesson_1);
        Button purple = dialogView.findViewById(R.id.button_lesson_2);
        Button purpleDe = dialogView.findViewById(R.id.button_lesson_3);
        Button pink = dialogView.findViewById(R.id.button_lesson_4);
        Button yellow = dialogView.findViewById(R.id.button_lesson_6);
        Button blue = dialogView.findViewById(R.id.button_lesson_7);
        Button green = dialogView.findViewById(R.id.button_lesson_8);
        Button white = dialogView.findViewById(R.id.button_lesson_9);
        black.setOnClickListener(this);
        purple.setOnClickListener(this);
        purpleDe.setOnClickListener(this);
        pink.setOnClickListener(this);
        yellow.setOnClickListener(this);
        blue.setOnClickListener(this);
        green.setOnClickListener(this);
        white.setOnClickListener(this);

        builder = new AlertDialog.Builder(this);
        final ViewGroup viewGroup = (ViewGroup) dialogView.getParent();
        if(viewGroup!=null) viewGroup.removeAllViews();
        builder.setView(dialogView).setTitle("已选择主题："+getThemeName(viewModel.getTheme()));
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                viewModel.setTheme(themeNum);
                viewModel.saveTheme();
                Snackbar.make(binding.appSettingLayout,"设置成功，下次启动生效~",Snackbar.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) { }
        });
        dialog = builder.create();
        dialog.show();
    }

    private String getThemeName(int themeNum){
        switch (themeNum){
            case 1:return "黑色";
            case 2:return "浅紫色";
            case 3:return "深紫色";
            case 4:return "粉红色";
            case 5:return "黄色";
            case 6:return "蓝色";
            case 7:return "绿色";
            case 8:return "白色";
            default:return "";
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Uri imageUri;
        File imageFile = null;
        if(requestCode==TagHelper.APPSETTING&&resultCode==RESULT_OK){
            Uri uri = data.getData();// 获取图片的uri
            Intent intent_gallery_crop = new Intent("com.android.camera.action.CROP");
            intent_gallery_crop.setDataAndType(uri, "image/*");
            intent_gallery_crop.putExtra("crop", "true");
            intent_gallery_crop.putExtra("scale", true);
            intent_gallery_crop.putExtra("aspectX", 9);
            intent_gallery_crop.putExtra("aspectY", 16);
            intent_gallery_crop.putExtra("return-data", false);
            // 创建文件保存裁剪的图片
            imageFile = FileHelper.userBackgroundToFile(imageFile,getApplicationContext());
            imageUri = Uri.fromFile(imageFile);
            if (imageUri != null){
                intent_gallery_crop.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent_gallery_crop.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            }
            startActivityForResult(intent_gallery_crop,TagHelper.APPSETTING2);
        }
        if(requestCode==TagHelper.APPSETTING&&resultCode==RESULT_OK){
            FileHelper.userBackgroundToFile(imageFile,getApplicationContext());
            binding.checkBoxEverydayBackground.setChecked(false);
            viewModel.getEverydayBackground().setValue(false);
            viewModel.saveEverydayBackground();
            setResult(TagHelper.APPSETTING);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case TagHelper.APPSETTING:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivityForResult(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI),TagHelper.APPSETTING);
                } else {
                    Snackbar.make(binding.appSettingLayout,"您未授予储存权限",Snackbar.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        viewModel.getEditor().apply();
    }
}
